package com.i8office.android.zhihuixinwu.ui.schedule;

import android.app.DatePickerDialog;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.DrawableRes;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.AppCompatButton;
import android.support.v7.widget.AppCompatEditText;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.widget.DatePicker;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.blankj.utilcode.util.KeyboardUtils;
import com.cyan.tools.annotation.ActivityFragmentInject;
import com.cyan.tools.base.BaseActivity;
import com.example.menhoo.toollibrary.common.utils.DisplayUtil;
import com.gyf.barlibrary.ImmersionBar;
import com.i8office.android.zhihuixinwu.R;
import com.i8office.android.zhihuixinwu.event.RefreshCalendarEvent;
import com.i8office.android.zhihuixinwu.module.contract.CalendarContract;
import com.i8office.android.zhihuixinwu.module.presenter.AddEventPresenter;

import org.greenrobot.eventbus.EventBus;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

@ActivityFragmentInject(contentViewId = R.layout.activity_add_event,
        menuId = R.menu.ok)
public class AddEventActivity extends BaseActivity<CalendarContract.AddEventPresenter> implements ChooseTimeDialogFragment.OnChooseTime, CalendarContract.AddEventView {
    @BindView(R.id.tv_date)
    TextView mDate;
    @BindView(R.id.tv_time)
    TextView mTime;
    @BindView(R.id.title)
    TextView mTvTitle;
    @BindView(R.id.tv_remind)
    TextView mRemind;
    @BindView(R.id.et_title)
    AppCompatEditText mTitle;
    @BindView(R.id.delete)
    AppCompatButton mDelete;
    @BindView(R.id.et_location)
    AppCompatEditText mLocation;
    private int sH = 0;
    private int sM = 0;
    private int rD = 0;
    private int rH = 0;
    private int rM = 0;
    private EventItem eventItem;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mPresenter = new AddEventPresenter(this);
        eventItem = (EventItem) getIntent().getSerializableExtra("event");
        ButterKnife.bind(this);
        ImmersionBar.with(this)
                .statusBarDarkFont(true, 0.2f) //原理：如果当前设备支持状态栏字体变色，会设置状态栏字体为黑色，如果当前设备不支持状态栏字体变色，会使当前状态栏加上透明度，否则不执行透明度
                .init();
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        setDrawableLeft(mDate, R.drawable.icon_date);
        setDrawableLeft(mTime, R.drawable.icon_time);
        setDrawableLeft(mLocation, R.drawable.icon_location);
        if (eventItem != null) {
            mTitle.setText(eventItem.getTitle());
            mLocation.setText(eventItem.getLocation());
            mDate.setText(eventItem.getStartDateString());
            if (TextUtils.isEmpty(eventItem.getStartTimeString()) || eventItem.getStartTimeString().equals("--:--")) {
                mTime.setText("");
                mRemind.setText("");
            } else {
                mTime.setText(eventItem.getStartTimeString());
                if (TextUtils.isEmpty(eventItem.getRemindTimeOffsetMinutes())) {
                    mRemind.setText("");
                } else {
                    mRemind.setText(eventItem.getRemindTimeString());
                    int min = Integer.parseInt(eventItem.getRemindTimeOffsetMinutes());
                    if (min < 0) {
                        rD = 0;
                        rH = 0;
                        rM = 0;
                    } else if (min >= 60 * 24) {
                        rD = min / (60 * 24);
                    } else if (min >= 60) {
                        rH = min / 60;
                    } else {
                        rM = min;
                    }
                }

            }
            sH = eventItem.getStartHour();
            sM = eventItem.getStartMinute();


            mDelete.setVisibility(View.VISIBLE);
        } else {
            mDate.setText(getIntent().getStringExtra("date"));
        }
        mTvTitle.setText(eventItem == null ? R.string.add_event : R.string.event_detail);
    }

    private void setDrawableLeft(TextView view, @DrawableRes int drawableRes) {
        Drawable drawable = ContextCompat.getDrawable(this, drawableRes);
        drawable.setBounds(0, 0, DisplayUtil.dip2px(this, 30), DisplayUtil.dip2px(this, 30));
        view.setCompoundDrawables(drawable, null, null, null);
    }

    @OnClick(R.id.delete)
    void delete() {
        if (eventItem != null) {
            new MaterialDialog.Builder(this)
                    .content(R.string.delete_event)
                    .positiveText(R.string.confirm)
                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog materialDialog, @NonNull DialogAction dialogAction) {
                            mPresenter.removeEvent(eventItem.getTaskID(), "");
                        }
                    })
                    .negativeText(R.string.cancel)
                    .show();

        }
    }

    @OnClick(R.id.tv_date)
    void chooseDate() {
        final Calendar calendar = Calendar.getInstance();
        // 日期对话框
        DatePickerDialog dialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                calendar.set(year, monthOfYear, dayOfMonth);
                mDate.setText(format.format(calendar.getTimeInMillis()));
            }
        }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
        dialog.show();

    }

    @OnClick(R.id.choose_time)
    void chooseTime() {
        String remind = mRemind.getText().toString();
        if (eventItem != null) {
            String[] strs = getResources().getStringArray(R.array.reminds);
            if (eventItem.isIsRemind()) {
                if (rD == 0 && rH == 0 && rM == 0) {
                    if (TextUtils.isEmpty(eventItem.getRemindTimeOffsetMinutes())) {
                        remind = strs[0];
                    } else {
                        int min = Integer.parseInt(eventItem.getRemindTimeOffsetMinutes());
                        if (min < 0) {
                            remind = eventItem.getRemindTimeString();
                        } else {
                            remind = strs[1];
                        }
                    }
                } else if (rM == 10) {
                    remind = strs[2];
                } else if (rM == 20) {
                    remind = strs[3];
                } else if (rM == 30) {
                    remind = strs[4];
                } else if (rH == 1) {
                    remind = strs[5];
                } else if (rH == 2) {
                    remind = strs[6];
                } else if (rH == 4) {
                    remind = strs[7];
                } else if (rH == 8) {
                    remind = strs[8];
                } else if (rH == 12) {
                    remind = strs[9];
                } else if (rD == 1) {
                    remind = strs[10];
                } else {
                    remind = strs[11];
                }
            } else {
                remind = strs[0];
            }
        }
        ChooseTimeDialogFragment.newInstance(mTime.getText().toString(), remind)
                .show(getSupportFragmentManager(), "ChooseTimeDialogFragment");
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
            case R.id.add://确定
                if (eventItem != null) {
                    updateEvent();
                } else {
                    addEvent();
                }
                break;
        }
        return false;
    }

    //添加日程
    private void addEvent() {
        String startDate = mDate.getText().toString();
        String title = mTitle.getText().toString();
//        int timeQuantum = apm;
        String location = mLocation.getText().toString();
        int hour = sH;
        int minute = sM;
        int dayOffset = rD;
        int hourOffset = rH;
        int minuteOffset = rM;
        if (TextUtils.isEmpty(title)) {
            toast(R.string.title_error);
            return;
        }
        if (TextUtils.isEmpty(startDate)) {
            toast(R.string.start_date_error);
            return;
        }
        Map<String, String> params = new HashMap<>();
        params.put("startDate", startDate);
        params.put("title", title);
//        params.put("timeQuantum", String.valueOf(timeQuantum));
        params.put("location", location);
        if (!TextUtils.isEmpty(mTime.getText().toString())) {
            params.put("hour", String.valueOf(hour));
            params.put("minute", String.valueOf(minute));
        } else {
            params.put("hour", "");
            params.put("minute", "");
        }
        if (!TextUtils.isEmpty(mRemind.getText().toString())) {
            params.put("dayOffset", String.valueOf(dayOffset));
            params.put("hourOffset", String.valueOf(hourOffset));
            params.put("minuteOffset", String.valueOf(minuteOffset));
        } else {
            params.put("dayOffset", "");
            params.put("hourOffset", "");
            params.put("minuteOffset", "");
        }
        mPresenter.addEvent(params);
    }

    //修改日程
    private void updateEvent() {
        String startDate = mDate.getText().toString();
        String title = mTitle.getText().toString();
//        int timeQuantum = apm;
        String location = mLocation.getText().toString();
        int hour = sH;
        int minute = sM;
        int dayOffset = rD;
        int hourOffset = rH;
        int minuteOffset = rM;
        if (TextUtils.isEmpty(title)) {
            toast(R.string.title_error);
            return;
        }
        if (TextUtils.isEmpty(startDate)) {
            toast(R.string.start_date_error);
            return;
        }
        if (TextUtils.isEmpty(mTime.getText().toString()) && !TextUtils.isEmpty(mRemind.getText().toString())) {
            toast(R.string.remind_time_error);
            return;
        }
        Map<String, String> params = new HashMap<>();
        params.put("id", eventItem.getTaskID());
        params.put("startDate", startDate);
        params.put("title", title);
//        params.put("timeQuantum", String.valueOf(timeQuantum));
        params.put("location", location);
        if (!TextUtils.isEmpty(mTime.getText().toString())) {
            params.put("hour", String.valueOf(hour));
            params.put("minute", String.valueOf(minute));
        } else {
            params.put("hour", "");
            params.put("minute", "");
        }
        if (!TextUtils.isEmpty(mRemind.getText().toString())) {
            params.put("dayOffset", String.valueOf(dayOffset));
            params.put("hourOffset", String.valueOf(hourOffset));
            params.put("minuteOffset", String.valueOf(minuteOffset));
        } else {
            params.put("dayOffset", "");
            params.put("hourOffset", "");
            params.put("minuteOffset", "");
        }
        if (eventItem != null && eventItem.getCanEdit() == 0) {
            mPresenter.updateOtherEvent(params);
        } else {
            mPresenter.updateEvent(params);
        }
    }

    @Override
    public void onChooseTime(String time, int h, int m, int apm) {
        mTime.setText(time);
        this.sH = h;
        this.sM = m;
    }

    @Override
    public void onChooseRemind(String remind, int d, int h, int m) {
        mRemind.setText(remind);
        this.rD = d;
        this.rH = h;
        this.rM = m;
    }

    @Override
    public void addSuccess() {
        //添加成功刷新列表和日历
        EventBus.getDefault().post(new RefreshCalendarEvent());
        finish();
    }

    @Override
    public void deleteSuccess() {
        addSuccess();
    }

    @Override
    public void showProgress() {
    }

    @Override
    public void hideProgress() {

    }

    @Override
    public void onDestroy() {
        if (KeyboardUtils.isSoftInputVisible(this)) {
            KeyboardUtils.toggleSoftInput();
        }
        super.onDestroy();
    }
}
